<script setup>
import { ref, onMounted, onBeforeUnmount, computed, shallowRef, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { useDocumentStore } from '@/stores/document';
// 导入wangEditor富文本编辑器到文档编辑页面
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
// 导入Element Plus的消息组件和对话框组件
import { ElMessage, ElMessageBox } from 'element-plus';
// 导入http模块
import http from '@/utils/http';
import DocumentVersionHistoryDialog from '@/components/DocumentVersionHistoryDialog.vue';
import DocumentVersionView from '@/components/DocumentVersionView.vue';
// 导入WebSocket管理器和协作面板
import wsManager from '@/utils/websocket';
import CollaborationPanel from '@/components/CollaborationPanel.vue';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const documentStore = useDocumentStore();

// 文档ID
const documentId = computed(() => route.params.id);

// 文档内容
const document = ref(null);
const documentTitle = ref('');
const documentContent = ref('');

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 编辑器内容
const editorValue = ref('');

// 编辑器配置
const editorConfig = {
  placeholder: '请输入文档内容...',
  MENU_CONF: {}
};

// AI生成相关
const isGeneratingAiContent = ref(false);
const aiPrompt = ref('');

// 协作者列表
const collaborators = ref([]);
const showCollaboratorsPanel = ref(false);

// 新增协作者表单
const newCollaboratorId = ref('');
const newCollaboratorPermission = ref('viewer'); // 默认为只读权限

// 用户搜索
const searchUserKeyword = ref('');
const searchUserResults = ref([]);
const selectedUser = ref(null);
const searchTimeout = ref(null);

// 历史版本相关
const showVersionHistoryDialog = ref(false);
const showVersionViewDialog = ref(false);
const selectedVersion = ref(null);

// 编辑状态
const isSaving = ref(false);
const isEditing = ref(false);
const lastSavedAt = ref(null);

// 当前用户的文档权限
const userPermission = ref(null);

// 自动保存计时器
let autoSaveTimer = null;

// 加载状态
const loading = ref(true);
const error = ref(null);

// 协作相关状态
const showCollaborationPanel = ref(false);
const isCollaborationConnected = ref(false);

const isApplyingRemoteChange = ref(false);
const pendingOperations = ref([]);

// 编辑器变化防抖
let editorChangeTimeout = null;
const EDITOR_CHANGE_DELAY = 300;

// 获取文档详情
const fetchDocument = async () => {
  loading.value = true;
  error.value = null;
  
  // 检查documentId是否有效
  if (!documentId.value) {
    error.value = '文档ID无效';
    loading.value = false;
    // 设置默认权限为只读
    userPermission.value = 'viewer';
    return;
  }
  
  try {
    await documentStore.fetchDocumentById(documentId.value);
    document.value = documentStore.currentDocument;
    
    if (document.value) {
      documentTitle.value = document.value.title;
      documentContent.value = document.value.content;
      editorValue.value = document.value.content; // 设置编辑器内容
      lastSavedAt.value = new Date();
      
      // 初步设置权限，后续会在 fetchCollaborators 中更精确设置
      const currentUserId = userStore.currentUser?.id;
      if (currentUserId && document.value.userId === currentUserId) {
        userPermission.value = 'admin'; // 文档创建者视为管理员
      } else {
        // 默认设置为只读权限，等待 fetchCollaborators 更新
        userPermission.value = 'viewer';
      }
    } else {
      error.value = '文档不存在或您没有权限访问';
      // 设置默认权限为只读
      userPermission.value = 'viewer';
    }
  } catch (err) {
    error.value = '获取文档失败';
    // 出错时设置默认权限为只读
    userPermission.value = 'viewer';
  } finally {
    loading.value = false;
  }
};

// 获取协作者列表
const fetchCollaborators = async () => {
  if (!documentId.value) {
    userPermission.value = 'viewer'; // 默认为查看者权限
    return;
  }
  
  try {
    await documentStore.fetchCollaborators(documentId.value);
    collaborators.value = documentStore.collaborators;
    
    // 获取当前用户的权限
    const currentUserId = userStore.currentUser?.id;
    
    if (currentUserId) {
      // 检查当前用户是否是文档创建者
      const userIdStr = String(currentUserId);
      const creatorIdStr = document.value?.userId ? String(document.value.userId) : null;
      
      if (document.value && creatorIdStr === userIdStr) {
        userPermission.value = 'admin'; // 文档创建者视为管理员
      } else {
        // 确保类型一致，将两边都转换为字符串进行比较
        const userCollaborator = collaborators.value.find(c => String(c.userId) === userIdStr);
        
        if (userCollaborator) {
          // 确保权限值是小写的，以匹配我们的权限检查
          const permissionValue = String(userCollaborator.permission).toLowerCase();
          userPermission.value = permissionValue;
        } else {
          userPermission.value = 'viewer'; // 用户不在协作者列表中，默认设置为只读权限
        }
      }
    } else {
      // 如果没有获取到当前用户ID，默认设置为只读权限
      userPermission.value = 'viewer';
    }
  } catch (err) {
    // 出错时也设置默认权限为只读
    userPermission.value = 'viewer';
  }
};

// 检查用户是否有编辑权限
const hasEditPermission = computed(() => {
  // 确保 userPermission 有值
  if (!userPermission.value) {
    return false; // 如果权限未定义或为null，默认没有编辑权限
  }
  
  // 确保使用小写字符串进行比较
  const permission = String(userPermission.value).toLowerCase();
  
  // 如果用户权限是editor或admin，则有编辑权限
  const hasPermission = permission === 'editor' || permission === 'admin';
  return hasPermission;
});

// 保存文档
const saveDocument = async () => {
  if (isSaving.value) {
    return;
  }
  
  // 检查documentId是否有效
  if (!documentId.value) {
    ElMessage({
      type: 'error',
      message: '保存失败：文档ID无效'
    });
    return;
  }
  
  // 检查用户是否有编辑权限
  if (!hasEditPermission.value) {
    ElMessage({
      type: 'error',
      message: '您没有权限执行此操作'
    });
    return;
  }
  
  isSaving.value = true;
  
  try {
    const success = await documentStore.updateDocument(documentId.value, {
      title: documentTitle.value,
      content: editorValue.value // 使用编辑器的内容
    });
    
    if (success) {
      lastSavedAt.value = new Date();
      // 显示成功消息
      ElMessage({
        type: 'success',
        message: '文档保存成功'
      });
    }
  } catch (err) {
    // 显示错误消息
    ElMessage({
      type: 'error',
      message: '文档保存失败: ' + (err.message || '未知错误')
    });
  } finally {
    isSaving.value = false;
  }
};

// 使用AI生成文档内容
const generateDocumentContentByAi = async () => {
  // 检查用户是否有编辑权限
  if (!hasEditPermission.value) {
    ElMessage({
      type: 'error',
      message: '您没有权限执行此操作'
    });
    return;
  }
  
  // 检查提示词是否为空
  if (!aiPrompt.value.trim()) {
    ElMessage({
      type: 'warning',
      message: '请输入提示词'
    });
    return;
  }
  
  isGeneratingAiContent.value = true;
  
  try {
    // 调用后端API生成文档内容
    const response = await http.post('/document/ai/generate', {
      prompt: aiPrompt.value
    });
    
    if (response.code === 0 && response.data) {
      // 将生成的内容插入到编辑器中
      const generatedContent = response.data;
      
      // 获取当前编辑器实例
      const editor = editorRef.value;
      if (!editor) {
        ElMessage({
          type: 'error',
          message: '编辑器实例不存在'
        });
        return;
      }
      
      // 将生成的内容格式化为HTML
      // 将纯文本内容中的换行符转换为<p>标签
      const formattedContent = generatedContent
        .split('\n\n')
        .map(paragraph => paragraph.trim())
        .filter(paragraph => paragraph)
        .map(paragraph => `<p>${paragraph}</p>`)
        .join('');
      
      // 获取当前编辑器的HTML内容
      const currentContent = editor.getHtml();
      
      // 如果编辑器已有内容，则在末尾添加生成的内容
      if (currentContent && currentContent !== '<p><br></p>') {
        // 在当前内容后添加新内容
        editor.setHtml(currentContent + formattedContent);
      } else {
        // 编辑器为空，直接设置内容
        editor.setHtml(formattedContent);
      }
      
      // 更新editorValue以保持同步
      editorValue.value = editor.getHtml();
      
      // 清空提示词
      aiPrompt.value = '';
      
      // 显示成功消息
      ElMessage({
        type: 'success',
        message: 'AI已生成文档内容'
      });
    } else {
      throw new Error(response.message || '生成失败');
    }
  } catch (err) {
    // 显示错误消息
    ElMessage({
      type: 'error',
      message: 'AI生成内容失败: ' + (err.message || '未知错误')
    });
  } finally {
    isGeneratingAiContent.value = false;
  }
};

// 保存文档版本
const saveVersionDocument = async () => {
  if (isSaving.value) {
    return;
  }
  
  // 检查documentId是否有效
  if (!documentId.value) {
    ElMessage({
      type: 'error',
      message: '保存版本失败：文档ID无效'
    });
    return;
  }
  
  // 检查用户是否有编辑权限
  if (!hasEditPermission.value) {
    ElMessage({
      type: 'error',
      message: '您没有权限执行此操作'
    });
    return;
  }
  
  try {
    // 弹出对话框让用户输入版本备注
    const { value: remark } = await ElMessageBox.prompt(
      '请输入此版本的备注信息',
      '保存版本',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputPlaceholder: '例如：修复了某个问题、添加了新功能等',
        inputValidator: (value) => {
          if (value.length > 1024) {
            return '备注长度不能超过1024个字符';
          }
          return true;
        },
        inputErrorMessage: '备注信息无效'
      }
    );
    
    // 用户点击了确认按钮，开始保存版本
    isSaving.value = true;
    
    // 调用保存版本的API
    const response = await http.post('/document/edit/saveVersion', {
      id: documentId.value,
      title: documentTitle.value,
      content: editorValue.value, // 使用编辑器的内容
      remark: remark // 添加用户输入的备注
    });
    
    if (response.data) {
      lastSavedAt.value = new Date();
      // 显示成功消息
      ElMessage({
        type: 'success',
        message: '文档版本保存成功'
      });
    }
  } catch (err) {
    // 如果是用户取消了输入，不显示错误
    if (err === 'cancel') {
      return;
    }
    
    // 显示错误消息
    ElMessage({
      type: 'error',
      message: '文档版本保存失败: ' + (err.message || '未知错误')
    });
  } finally {
    isSaving.value = false;
  }
};

// 下载文档
const downloadDocument = (fileType = 'html') => {
  if (!documentId.value || !document.value) {
    ElMessage({
      type: 'error',
      message: '无法下载：文档数据不完整'
    });
    return;
  }

  // 检查浏览器环境
  if (typeof window === 'undefined' || typeof document === 'undefined') {
    ElMessage({
      type: 'error',
      message: '下载功能仅在浏览器环境中可用'
    });
    return;
  }

  try {
    // 检查Blob支持
    if (!window.Blob) {
      ElMessage({
        type: 'error',
        message: '您的浏览器不支持文件下载功能'
      });
      return;
    }
    
    // 检查URL.createObjectURL支持
    if (!window.URL || !window.URL.createObjectURL) {
      ElMessage({
        type: 'error',
        message: '您的浏览器不支持文件下载功能'
      });
      return;
    }
    
    let content, mimeType, fileName;
    const title = documentTitle.value || '无标题文档';
    const docContent = editorValue.value || '';
    
    // 根据文件类型生成不同格式的内容
    switch (fileType) {
      case 'html':
        content = `<!DOCTYPE html>\n<html lang="zh-CN">\n<head>\n  <meta charset="UTF-8">\n  <meta name="viewport" content="width=device-width, initial-scale=1.0">\n  <title>${title}</title>\n  <style>\n    body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; line-height: 1.6; }\n    h1 { color: #333; border-bottom: 2px solid #eee; padding-bottom: 10px; }\n  </style>\n</head>\n<body>\n  <h1>${title}</h1>\n  <div>${docContent}</div>\n</body>\n</html>`;
        mimeType = 'text/html;charset=utf-8';
        fileName = `${title}.html`;
        break;
      
      case 'md':
        content = `# ${title}\n\n${docContent.replace(/<[^>]*>/g, '')}`;
        mimeType = 'text/markdown;charset=utf-8';
        fileName = `${title}.md`;
        break;
      
      case 'doc':
        // 生成简单的RTF格式，可被Word打开
        const rtfContent = docContent.replace(/<[^>]*>/g, '').replace(/\n/g, '\\par ');
        content = `{\\rtf1\\ansi\\deff0 {\\fonttbl {\\f0 Times New Roman;}}\\f0\\fs24 \\b ${title}\\b0\\par\\par ${rtfContent}}`;
        mimeType = 'application/rtf;charset=utf-8';
        fileName = `${title}.rtf`;
        break;
      
      default:
        content = `# ${title}\n\n${docContent}`;
        mimeType = 'text/html;charset=utf-8';
        fileName = `${title}.html`;
    }
    
    // 创建Blob对象
    const blob = new Blob([content], { type: mimeType });
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = window.document.createElement('a');
    link.href = url;
    link.download = fileName;
    
    // 设置链接样式（隐藏）
    link.style.display = 'none';
    
    // 触发下载
    window.document.body.appendChild(link);
    link.click();
    
    // 清理
    setTimeout(() => {
      window.document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    }, 100);
    
    const formatNames = {
      html: 'HTML',
      md: 'Markdown',
      doc: 'Word'
    };
    
    ElMessage({
      type: 'success',
      message: `${formatNames[fileType]}格式文档下载成功`
    });
  } catch (error) {
    console.error('下载文档失败:', error);
    ElMessage({
      type: 'error',
      message: '下载文档失败: ' + (error.message || '未知错误')
    });
  }
};

// 自动保存
const setupAutoSave = () => {
  // 每30秒自动保存一次
  autoSaveTimer = setInterval(() => {
    if (isEditing.value && documentId.value) {
      saveDocument();
    }
  }, 30000);
};

// 初始化协作功能
const initializeCollaboration = () => {
  // 检查用户是否已登录
  if (!userStore.isLoggedIn) {
    console.warn('用户未登录，无法启用协作功能');
    return;
  }
  
  // 连接WebSocket
  wsManager.connect(documentId.value);
  
  // 设置WebSocket事件处理器
  setupWebSocketHandlers();
};

// 设置WebSocket事件处理器
const setupWebSocketHandlers = () => {
  // 连接成功
  wsManager.on('connected', () => {
    isCollaborationConnected.value = true;
    ElMessage.success('协作连接已建立');
  });
  
  // 连接断开
  wsManager.on('disconnected', () => {
    isCollaborationConnected.value = false;
    ElMessage.warning('协作连接已断开');
  });
  
  // 接收到文档内容
  wsManager.on('documentContent', (data) => {
    if (data.content && !isApplyingRemoteChange.value) {
  
      // 如果内容不同，更新编辑器内容
      if (editorValue.value !== data.content) {
        isApplyingRemoteChange.value = true;
        editorValue.value = data.content;
        documentContent.value = data.content;
        setTimeout(() => {
          isApplyingRemoteChange.value = false;
        }, 100);
      }
    }
  });
  
  // 接收到编辑操作
  wsManager.on('editAction', (data) => {
    if (data.user && data.user.id !== userStore.currentUser?.id) {
      applyRemoteEdit(data);
    }
  });
  
  // 版本保存成功
  wsManager.on('versionSaved', (data) => {
    ElMessage.success('文档保存成功');
  });
  
  // 错误处理
  wsManager.on('error', (data) => {
    ElMessage.error(data.message || '协作过程中发生错误');
  });
};

// DOM点错误处理函数
const handleDOMPointError = (error) => {
  console.warn('检测到DOM点解析错误，尝试恢复编辑器状态:', error);
  
  try {
    // 强制重新渲染编辑器内容
    if (editorRef.value) {
      const currentContent = editorValue.value || '';
      
      // 使用编辑器API重新设置内容
      editorRef.value.setHtml(currentContent);
      
      ElMessage({
        type: 'warning',
        message: '编辑器状态已自动恢复',
        duration: 2000
      });
    }
  } catch (recoveryError) {
    console.error('编辑器状态恢复失败:', recoveryError);
    
    // 如果恢复失败，提示用户刷新页面
    ElMessage({
      type: 'error',
      message: '编辑器出现异常，建议刷新页面',
      duration: 5000
    });
  }
};

// 应用远程编辑操作
const applyRemoteEdit = (data) => {
  if (isApplyingRemoteChange.value) {
    return;
  }
  
  isApplyingRemoteChange.value = true;
  
  try {
    const { operation, content, position } = data;
    let currentContent = editorValue.value || '';
    let newContent = currentContent;
    
    switch (operation) {
      case 'INSERT':
        newContent = currentContent.substring(0, position) + content + currentContent.substring(position);
        break;
      case 'DELETE':
        const endPos = position + content.length;
        newContent = currentContent.substring(0, position) + currentContent.substring(endPos);
        break;
      case 'REPLACE':
        const replaceEnd = position + content.length;
        newContent = currentContent.substring(0, position) + content + currentContent.substring(replaceEnd);
        break;
    }
    
    // 安全地更新编辑器内容
    try {
      if (editorRef.value && editorRef.value.setHtml) {
        editorRef.value.setHtml(newContent);
      } else {
        editorValue.value = newContent;
      }
      documentContent.value = newContent;
    } catch (domError) {
      console.error('更新编辑器内容时发生DOM错误:', domError);
      
      // 如果是DOM点解析错误，使用错误处理函数
      if (domError.message && domError.message.includes('Cannot resolve a DOM point')) {
        handleDOMPointError(domError);
      } else {
        // 其他错误，直接设置值
        editorValue.value = newContent;
        documentContent.value = newContent;
      }
    }
    
  } catch (error) {
    console.error('应用远程编辑操作失败:', error);
    
    // 如果是DOM点解析错误，使用专门的处理函数
    if (error.message && error.message.includes('Cannot resolve a DOM point')) {
      handleDOMPointError(error);
    }
  } finally {
    setTimeout(() => {
      isApplyingRemoteChange.value = false;
    }, 100);
  }
};

// 发送编辑操作到其他用户
const sendEditOperation = (operation, content, position) => {
  if (isApplyingRemoteChange.value || !hasEditPermission.value) {
    return;
  }
  
  wsManager.sendEditAction(operation, content, position);
};

// 切换协作面板显示
const toggleCollaborationPanel = () => {
  showCollaborationPanel.value = !showCollaborationPanel.value;
};

// 处理协作面板的保存版本请求
const handleCollaborationSaveVersion = () => {
  saveVersionDocument();
};

// 处理标题变化
const handleTitleChange = () => {
  isEditing.value = true;
};

// 处理内容变化
const handleContentChange = () => {
  isEditing.value = true;
};

// 编辑器内容变化时触发
const handleEditorChange = () => {
  // 只有在有编辑权限时才设置编辑状态
  if (hasEditPermission.value) {
    isEditing.value = true;
    
    // 如果不是应用远程更改，则发送编辑操作
    if (!isApplyingRemoteChange.value) {
      // 清除之前的防抖计时器
      if (editorChangeTimeout) {
        clearTimeout(editorChangeTimeout);
      }
      
      // 设置防抖，避免频繁发送
      editorChangeTimeout = setTimeout(() => {
        try {
          const currentContent = editorValue.value || '';
          const previousContent = documentContent.value || '';
          
          // 简单的差异检测和操作发送
          if (currentContent !== previousContent) {
            // 这里简化处理，发送整个内容替换操作
            // 在实际应用中，可以使用更复杂的差异算法
            sendEditOperation('REPLACE', currentContent, 0);
            documentContent.value = currentContent;
          }
        } catch (error) {
          console.error('编辑器变化处理失败:', error);
          // 如果是DOM点解析错误，尝试重新同步编辑器状态
          if (error.message && error.message.includes('Cannot resolve a DOM point')) {
            handleDOMPointError(error);
          }
        }
      }, EDITOR_CHANGE_DELAY);
    }
  }
};

// 编辑器创建完成时触发
const handleEditorCreated = (editor) => {
  editorRef.value = editor;
  
  // 如果用户没有编辑权限，禁用编辑器
  if (!hasEditPermission.value) {
    editor.disable();
  } else {
    editor.enable();
  }
  
  // 添加全局错误监听器，捕获DOM点解析错误
  try {
    // 监听编辑器内部的错误事件
    const editorContainer = editor.getEditableContainer();
    if (editorContainer) {
      // 使用事件委托捕获可能的错误
      editorContainer.addEventListener('error', (event) => {
        console.error('编辑器容器错误:', event);
        if (event.error && event.error.message && event.error.message.includes('Cannot resolve a DOM point')) {
          handleDOMPointError(event.error);
        }
      }, true);
    }
    
    // 保存并添加全局未捕获错误监听器
     originalErrorHandler = window.onerror;
     window.onerror = (message, source, lineno, colno, error) => {
       if (message && message.includes && message.includes('Cannot resolve a DOM point')) {
         handleDOMPointError(error || new Error(message));
         return true; // 阻止默认错误处理
       }
       
       // 调用原始错误处理器
       if (originalErrorHandler) {
         return originalErrorHandler(message, source, lineno, colno, error);
       }
       return false;
     };
     
     // 保存并添加Promise未捕获错误监听器
     originalUnhandledRejection = window.onunhandledrejection;
     window.onunhandledrejection = (event) => {
       if (event.reason && event.reason.message && event.reason.message.includes('Cannot resolve a DOM point')) {
         handleDOMPointError(event.reason);
         event.preventDefault(); // 阻止默认处理
         return;
       }
       
       // 调用原始处理器
       if (originalUnhandledRejection) {
         originalUnhandledRejection(event);
       }
     };
  } catch (error) {
    console.error('设置编辑器错误监听器失败:', error);
  }
};

// 添加协作者
const addCollaborator = async (userId, permission) => {
  try {
    const success = await documentStore.addCollaborator(documentId.value, userId, permission);
    if (success) {
      // 刷新协作者列表
      await fetchCollaborators();
      // 显示成功消息
      ElMessage({
        type: 'success',
        message: '添加协作者成功'
      });
    }
  } catch (err) {
    // 显示错误消息
    ElMessage({
      type: 'error',
      message: '添加协作者失败'
    });
  }
};

// 处理用户搜索
const handleSearchUser = () => {
  // 清除之前的定时器
  if (searchTimeout.value) {
    clearTimeout(searchTimeout.value);
  }
  
  // 如果搜索关键词为空，清空搜索结果
  if (!searchUserKeyword.value.trim()) {
    searchUserResults.value = [];
    return;
  }
  
  // 设置新的定时器，防止频繁请求
  searchTimeout.value = setTimeout(async () => {
    try {
      // 调用后端API搜索用户
      const response = await http.post('/user/list/page/vo', {
        userName: searchUserKeyword.value,
        pageSize: 5,
        current: 1
      });
      
      if (response.data && response.data.records) {
        searchUserResults.value = response.data.records;
      } else {
        searchUserResults.value = [];
      }
    } catch (err) {
      ElMessage({
        type: 'error',
        message: '搜索用户失败'
      });
      searchUserResults.value = [];
    }
  }, 300); // 300ms延迟，减少请求频率
};

// 选择用户
const selectUser = (user) => {
  selectedUser.value = user;
  newCollaboratorId.value = user.id.toString();
  searchUserResults.value = [];
  searchUserKeyword.value = '';
};

// 清除选择的用户
const clearSelectedUser = () => {
  selectedUser.value = null;
  newCollaboratorId.value = '';
};

// 处理添加协作者按钮点击
const handleAddCollaborator = async () => {
  // 验证输入
  if (!newCollaboratorId.value) {
    ElMessage({
      type: 'warning',
      message: '请输入用户ID或选择一个用户'
    });
    return;
  }
  
  // 直接使用字符串形式的ID，不使用parseInt转换
  try {
    const userId = newCollaboratorId.value;
    
    // 调用添加协作者方法
    await addCollaborator(userId, newCollaboratorPermission.value);
    
    // 清空输入
    newCollaboratorId.value = '';
    newCollaboratorPermission.value = 'viewer';
    selectedUser.value = null;
  } catch (err) {
    ElMessage({
      type: 'error',
      message: '添加协作者失败: ' + err.message
    });
  }
};

// 更新协作者权限
const updateCollaboratorPermission = async (id, permission) => {
  try {
    const success = await documentStore.updateCollaboratorPermission(id, permission);
    if (success) {
      // 刷新协作者列表
      await fetchCollaborators();
      // 显示成功消息
      ElMessage({
        type: 'success',
        message: '更新权限成功'
      });
    }
  } catch (err) {
    // 显示错误消息
    ElMessage({
      type: 'error',
      message: '更新权限失败'
    });
  }
};

// 移除协作者
const removeCollaborator = async (id) => {
  try {
    const success = await documentStore.removeCollaborator(id, documentId.value);
    if (success) {
      // 刷新协作者列表
      await fetchCollaborators();
      // 显示成功消息
      ElMessage({
        type: 'success',
        message: '移除协作者成功'
      });
    }
  } catch (err) {
    // 显示错误消息
    ElMessage({
      type: 'error',
      message: '移除协作者失败'
    });
  }
};

// 返回文档列表
const goBack = () => {
  router.push('/documents');
};

// 切换协作者面板
const toggleCollaboratorsPanel = () => {
  showCollaboratorsPanel.value = !showCollaboratorsPanel.value;
  
  if (showCollaboratorsPanel.value) {
    fetchCollaborators();
  }
};

// 组件挂载时获取数据
onMounted(async () => {
  // 首先初始化用户信息
  await userStore.initUser();
  
  await fetchDocument();
  await fetchCollaborators();
  setupAutoSave();
  
  // 初始化WebSocket协作功能
  if (documentId.value) {
    initializeCollaboration();
  }
});

// 监听编辑权限变化，更新编辑器状态
watch(hasEditPermission, (newValue) => {
  if (editorRef.value) {
    if (newValue) {
      editorRef.value.enable();
    } else {
      editorRef.value.disable();
    }
  }
});

// 存储原始错误处理器的引用
let originalErrorHandler = null;
let originalUnhandledRejection = null;

// 组件卸载前清理
onBeforeUnmount(() => {
  // 清除自动保存计时器
  if (autoSaveTimer) {
    clearInterval(autoSaveTimer);
  }
  
  // 清除编辑器变化防抖计时器
  if (editorChangeTimeout) {
    clearTimeout(editorChangeTimeout);
  }
  
  // 如果有未保存的更改，保存一次
  if (isEditing.value && documentId.value) {
    saveDocument();
  }
  
  // 断开WebSocket连接
  wsManager.disconnect();
  
  // 恢复原始错误处理器
  if (originalErrorHandler !== null) {
    window.onerror = originalErrorHandler;
  }
  if (originalUnhandledRejection !== null) {
    window.onunhandledrejection = originalUnhandledRejection;
  }
  
  // 销毁编辑器
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<template>
  <div class="document-edit-container">
    <!-- 顶部工具栏 -->
    <div class="document-toolbar">
      <div class="toolbar-left">
        <button @click="goBack" class="back-btn">
          <span class="icon">←</span> 返回
        </button>
        <div v-if="!loading && !error" class="document-status">
          <span v-if="isSaving">保存中...</span>
          <span v-else-if="lastSavedAt">上次保存: {{ lastSavedAt.toLocaleTimeString() }}</span>
        </div>
      </div>
      
      <div class="toolbar-right">
        <div v-if="!loading && !error" class="download-dropdown">
          <button 
            @click="downloadDocument('html')" 
            class="download-btn" 
            title="下载HTML文档"
          >
            <span class="icon">📥</span> 下载
          </button>
          <div class="dropdown-content">
            <button @click="downloadDocument('html')" class="dropdown-item">
              <span class="format-icon">🌐</span> HTML格式
            </button>
            <button @click="downloadDocument('md')" class="dropdown-item">
              <span class="format-icon">📝</span> Markdown格式
            </button>
            <button @click="downloadDocument('doc')" class="dropdown-item">
              <span class="format-icon">📄</span> Word格式
            </button>
          </div>
        </div>
        
        <button 
          v-if="!loading && !error" 
          @click="() => showVersionHistoryDialog = true" 
          class="history-version-btn" 
        >
          历史版本
        </button>
        
        <button 
          v-if="!loading && !error" 
          @click="saveVersionDocument" 
          class="save-version-btn" 
          :disabled="isSaving || !isEditing || !hasEditPermission"
        >
          保存版本
        </button>
        
        <button 
          v-if="!loading && !error" 
          @click="saveDocument" 
          class="save-btn" 
          :disabled="isSaving || !isEditing || !hasEditPermission"
        >
          {{ isSaving ? '保存中...' : '保存' }}
        </button>
        
        <button 
          v-if="!loading && !error" 
          @click="toggleCollaborationPanel" 
          class="collaboration-btn"
          :class="{ 'active': showCollaborationPanel }"
        >
          {{ isCollaborationConnected ? '🟢' : '🔴' }} 协作
        </button>
        
        <button 
          v-if="!loading && !error" 
          @click="toggleCollaboratorsPanel" 
          class="collaborators-btn"
        >
          协作者
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-placeholder">
      <p>加载中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-state">
      <p>{{ error }}</p>
      <button @click="goBack" class="btn-primary">返回文档列表</button>
    </div>

    <!-- 文档编辑区 -->
    <div v-else class="document-editor">
      <!-- 权限提示标签 -->
      <div class="permission-badge" :class="{
        'viewer-permission': userPermission === 'viewer',
        'editor-permission': userPermission === 'editor',
        'admin-permission': userPermission === 'admin'
      }">
        <span class="permission-icon">{{ 
          userPermission === 'viewer' ? '👁️' : 
          userPermission === 'editor' ? '✏️' : 
          userPermission === 'admin' ? '🔑' : '❓' 
        }}</span>
        <span class="permission-text">{{ 
          userPermission === 'viewer' ? '您在此文档中的权限：只读' : 
          userPermission === 'editor' ? '您在此文档中的权限：可编辑' : 
          userPermission === 'admin' ? '您在此文档中的权限：管理员' : '未知权限' 
        }}</span>
      </div>
      
      <input 
        type="text" 
        v-model="documentTitle" 
        class="document-title-input" 
        placeholder="请输入标题"
        @input="handleTitleChange"
        :disabled="!hasEditPermission"
      />
      
      <div class="editor-container">
        <!-- AI生成内容区域 -->
        <div v-if="hasEditPermission" class="ai-generate-container">
          <div class="ai-generate-header">
            <span class="ai-icon">🤖</span>
            <span class="ai-title">AI助手</span>
          </div>
          <div class="ai-generate-content">
            <div class="ai-input-container">
              <input 
                type="text" 
                v-model="aiPrompt" 
                class="ai-prompt-input" 
                placeholder="输入提示词，让AI帮你生成文档内容..."
                :disabled="isGeneratingAiContent"
              />
              <button 
                @click="generateDocumentContentByAi" 
                class="ai-generate-btn" 
                :disabled="isGeneratingAiContent || !aiPrompt.trim()"
              >
                {{ isGeneratingAiContent ? '生成中...' : '生成内容' }}
              </button>
            </div>
            <div class="ai-tips">
              提示：输入您想要生成的文档内容描述，AI将为您生成相关内容。例如："写一篇关于人工智能在医疗领域应用的文章"
            </div>
          </div>
        </div>
        
        <!-- 工具栏 -->
        <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="editorConfig"
          mode="default"
        />
        <!-- 编辑器 -->
        <Editor
          style="height: 400px; overflow-y: hidden;"
          v-model="editorValue"
          :defaultConfig="editorConfig"
          :mode="hasEditPermission ? 'default' : 'simple'"
          @onCreated="handleEditorCreated"
          @onChange="handleEditorChange"
        />
      </div>
    </div>

    <!-- 协作者面板 -->
    <div v-if="showCollaboratorsPanel" class="collaborators-panel">
      <div class="panel-header">
        <h3>协作者</h3>
        <button @click="toggleCollaboratorsPanel" class="close-panel-btn">×</button>
      </div>
      
      <div class="panel-content">
        <div class="collaborators-list">
          <div v-if="collaborators.length === 0" class="empty-collaborators">
            <p>暂无协作者</p>
          </div>
          
          <div v-else class="collaborator-item" v-for="collaborator in collaborators" :key="collaborator.id">
            <div class="collaborator-info">
              <span class="collaborator-name">{{ collaborator.user ? collaborator.user.userName : '未知用户' }}</span>
              <span class="collaborator-permission">
                {{ 
                  collaborator.permission === 'viewer' ? '只读' : 
                  collaborator.permission === 'editor' ? '可编辑' : 
                  collaborator.permission === 'admin' ? '管理员' : '未知'
                }}
              </span>
            </div>
            
            <div class="collaborator-actions">
              <select 
                v-model="collaborator.permission" 
                @change="updateCollaboratorPermission(collaborator.id, collaborator.permission)"
                :disabled="userPermission !== 'admin'"
              >
                <option value="viewer">只读</option>
                <option value="editor">可编辑</option>
                <option value="admin">管理员</option>
              </select>
              
              <button 
                @click="removeCollaborator(collaborator.id)" 
                class="remove-collaborator-btn"
                :disabled="userPermission !== 'admin'"
              >
                移除
              </button>
            </div>
          </div>
        </div>
        
        <div class="add-collaborator-form" :class="{ 'disabled-form': userPermission !== 'admin' }">
          <h4>添加协作者</h4>
          <div v-if="userPermission !== 'admin'" class="permission-warning">
            只有管理员权限才能添加协作者
          </div>
          <div class="search-user-form">
            <input 
              type="text" 
              v-model="searchUserKeyword" 
              placeholder="搜索用户名" 
              @input="handleSearchUser"
              :disabled="userPermission !== 'admin'"
            />
            <div v-if="searchUserResults.length > 0" class="search-results">
              <div 
                v-for="user in searchUserResults" 
                :key="user.id" 
                class="search-result-item"
                @click="selectUser(user)"
              >
                <span>{{ user.userName }}</span>
                <span class="user-email">{{ user.userAccount }}</span>
              </div>
            </div>
          </div>
          <div class="form-group">
            <input 
              type="text" 
              v-model="newCollaboratorId" 
              placeholder="用户ID" 
              :disabled="selectedUser !== null || userPermission !== 'admin'"
            />
            <select v-model="newCollaboratorPermission" :disabled="userPermission !== 'admin'">
              <option value="viewer">只读</option>
              <option value="editor">可编辑</option>
              <option value="admin">管理员</option>
            </select>
            <button class="add-btn" @click="handleAddCollaborator" :disabled="userPermission !== 'admin'">添加</button>
          </div>
          <div v-if="selectedUser" class="selected-user">
            <span>已选择: {{ selectedUser.userName }}</span>
            <button class="clear-btn" @click="clearSelectedUser" :disabled="userPermission !== 'admin'">清除</button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 协作面板 -->
    <CollaborationPanel
      v-show="showCollaborationPanel"
      :documentId="documentId"
      :isConnected="isCollaborationConnected"

      @save-version="handleCollaborationSaveVersion"
      @toggle-panel="toggleCollaborationPanel"
    />
  </div>
  
  <!-- 历史版本对话框 -->
  <DocumentVersionHistoryDialog
    v-model:visible="showVersionHistoryDialog"
    :documentId="documentId"
    @view-version="(version) => {
      selectedVersion = version;
      showVersionViewDialog = true;
    }"
    @backtrack-success="(docId) => {
      fetchDocument(); // 重新获取文档内容
      isEditing.value = false; // 重置编辑状态
      showVersionHistoryDialog = false; // 关闭版本历史对话框
    }"
  />
  
  <!-- 版本详情对话框 -->
  <DocumentVersionView
    v-model:visible="showVersionViewDialog"
    :versionData="selectedVersion"
    @back-to-list="() => {
      showVersionViewDialog = false;
      showVersionHistoryDialog = true;
    }"
  />
</template>

<style scoped>
.document-edit-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 权限提示标签样式 */
.permission-badge {
  display: inline-flex;
  align-items: center;
  padding: 6px 12px;
  margin-bottom: 16px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

.permission-icon {
  margin-right: 8px;
  font-size: 16px;
}

.viewer-permission {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.editor-permission {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.admin-permission {
  background-color: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

/* 工具栏样式 */
.document-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 2rem;
  background-color: white;
  border-bottom: 1px solid #e5e7eb;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background-color: transparent;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s;
}

.back-btn:hover {
  background-color: #f3f4f6;
}

.document-status {
  font-size: 0.875rem;
  color: #6b7280;
}

.download-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: background-color 0.2s;
  margin-right: 0.5rem;
}

.download-btn:hover {
  background-color: #2563eb;
}

.download-btn .icon {
  font-size: 1rem;
}

/* 下载下拉菜单样式 */
.download-dropdown {
  position: relative;
  display: inline-block;
  margin-right: 0.5rem;
}

.download-dropdown:hover .dropdown-content {
  display: block;
}

.dropdown-content {
  display: none;
  position: absolute;
  top: 100%;
  left: 0;
  background-color: white;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  border-radius: 4px;
  z-index: 1000;
  border: 1px solid #e5e7eb;
  overflow: hidden;
}

.dropdown-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  width: 100%;
  padding: 0.75rem 1rem;
  background-color: white;
  color: #374151;
  border: none;
  text-align: left;
  font-size: 0.875rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.dropdown-item:hover {
  background-color: #f3f4f6;
}

.dropdown-item .format-icon {
  font-size: 1rem;
  width: 1.2rem;
  text-align: center;
}

.history-version-btn {
  background-color: #90ade7;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  margin-right: 0;
}

.history-version-btn:hover {
  background-color: #a6a9ad;
}

.save-version-btn {
  padding: 0.5rem 1rem;
  background-color: #10b981;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: background-color 0.2s;
  margin-right: 0;
}

.save-version-btn:hover:not(:disabled) {
  background-color: #059669;
}

.save-version-btn:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

.save-btn {
  padding: 0.5rem 1rem;
  background-color: #4f46e5;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: background-color 0.2s;
  margin-right: 0;
}

.save-btn:hover:not(:disabled) {
  background-color: #4338ca;
}

.save-btn:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

.collaboration-btn {
  padding: 0.5rem 1rem;
  background-color: transparent;
  border: 1px solid #10b981;
  color: #10b981;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.collaboration-btn:hover {
  background-color: #f0fdf4;
}

.collaboration-btn.active {
  background-color: #10b981;
  color: white;
}

.collaborators-btn {
  padding: 0.5rem 1rem;
  background-color: transparent;
  border: 1px solid #4f46e5;
  color: #4f46e5;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s;
}

.collaborators-btn:hover {
  background-color: #f5f5ff;
}

/* 文档编辑区样式 */
.document-editor {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 2rem;
  background-color: #f9fafb;
  overflow: auto;
}

.document-title-input {
  width: 100%;
  padding: 1rem 0;
  font-size: 1.875rem;
  font-weight: 600;
  color: #1f2937;
  border: none;
  border-bottom: 1px solid #e5e7eb;
  background-color: transparent;
  margin-bottom: 1.5rem;
}

.document-title-input:focus {
  outline: none;
  border-color: #4f46e5;
}

.editor-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: white;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
}

/* 协作者面板样式 */
.collaborators-panel {
  position: fixed;
  top: 0;
  right: 0;
  width: 350px;
  height: 100%;
  background-color: white;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.panel-header h3 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.close-panel-btn {
  background-color: transparent;
  border: none;
  font-size: 1.5rem;
  color: #6b7280;
  cursor: pointer;
}

.close-panel-btn:hover {
  color: #1f2937;
}

.panel-content {
  flex: 1;
  padding: 1.5rem;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.collaborators-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.empty-collaborators {
  text-align: center;
  color: #6b7280;
  padding: 1rem 0;
}

.collaborator-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  background-color: #f9fafb;
}

.collaborator-info {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.collaborator-name {
  font-weight: 500;
  color: #1f2937;
}

.collaborator-permission {
  font-size: 0.75rem;
  color: #6b7280;
}

.collaborator-actions {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.collaborator-actions select {
  padding: 0.25rem 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.75rem;
  background-color: white;
}

.collaborator-actions select:disabled,
.collaborator-actions button:disabled,
.add-collaborator-form input:disabled,
.add-collaborator-form select:disabled,
.add-collaborator-form button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background-color: #f5f5f5;
}

.remove-collaborator-btn {
  padding: 0.25rem 0.5rem;
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 0.75rem;
  cursor: pointer;
}

.remove-collaborator-btn:hover {
  background-color: #dc2626;
}

.add-collaborator-form {
  margin-top: auto;
  padding-top: 1rem;
  border-top: 1px solid #e5e7eb;
}

.add-collaborator-form h4 {
  font-size: 1rem;
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 0.75rem;
}

.add-collaborator-form.disabled-form {
  opacity: 0.8;
}

.permission-warning {
  background-color: #fff3cd;
  color: #856404;
  padding: 8px 12px;
  border-radius: 4px;
  margin-bottom: 15px;
  font-size: 14px;
  border-left: 4px solid #ffeeba;
}

.form-group {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 0.75rem;
}

.form-group input {
  flex: 1;
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.875rem;
}

.form-group input:disabled {
  background-color: #f3f4f6;
  cursor: not-allowed;
}

.form-group select {
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.875rem;
  background-color: white;
}

.add-btn {
  padding: 0.5rem 0.75rem;
  background-color: #4f46e5;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
}

.add-btn:hover {
  background-color: #4338ca;
}

.search-user-form {
  position: relative;
  margin-bottom: 0.75rem;
}

.search-user-form input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.875rem;
}

.search-results {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  max-height: 200px;
  overflow-y: auto;
  background-color: white;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  z-index: 10;
}

.search-result-item {
  display: flex;
  flex-direction: column;
  padding: 0.5rem;
  cursor: pointer;
  border-bottom: 1px solid #e5e7eb;
}

.search-result-item:last-child {
  border-bottom: none;
}

.search-result-item:hover {
  background-color: #f3f4f6;
}

.user-email {
  font-size: 0.75rem;
  color: #6b7280;
}

.selected-user {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem;
  background-color: #f3f4f6;
  border-radius: 4px;
  font-size: 0.875rem;
}

.clear-btn {
  padding: 0.25rem 0.5rem;
  background-color: transparent;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.75rem;
  cursor: pointer;
}

.clear-btn:hover {
  background-color: #f9fafb;
}

/* AI生成内容区域样式 */
.ai-generate-container {
  margin-top: 0rem;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.ai-generate-header {
  display: flex;
  align-items: center;
  padding: 0.75rem 1rem;
  background-color: #f3f4f6;
  border-bottom: 1px solid #e5e7eb;
}

.ai-icon {
  font-size: 1.25rem;
  margin-right: 0.5rem;
}

.ai-title {
  font-weight: 600;
  color: #374151;
}

.ai-generate-content {
  padding: 1rem;
  background-color: #ffffff;
}

.ai-input-container {
  display: flex;
  gap: 0.5rem;
}

.ai-prompt-input {
  flex: 1;
  padding: 0.75rem 1rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.875rem;
}

.ai-generate-btn {
  padding: 0.75rem 1rem;
  background-color: #4f46e5;
  color: white;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.ai-generate-btn:hover {
  background-color: #4338ca;
}

.ai-generate-btn:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

.ai-tips {
  margin-top: 0.75rem;
  font-size: 0.75rem;
  color: #6b7280;
  line-height: 1.25;
}

/* 加载和错误状态样式 */
.loading-placeholder,
.error-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 2rem;
  text-align: center;
  color: #6b7280;
}

.error-state p {
  margin-bottom: 1rem;
  color: #ef4444;
}

.btn-primary {
  display: inline-block;
  padding: 0.75rem 1.5rem;
  background-color: #4f46e5;
  color: white;
  border: 1px solid #4f46e5;
  border-radius: 4px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
  text-decoration: none;
}

.btn-primary:hover {
  background-color: #4338ca;
}
</style>